import datetime, jwt, time
from flask import jsonify
#from app.system.user import User
from app.comm.pub import RestEntity

privatekey="xiaoguizi1976"

def encode_auth_token(userid, logintime):
    """
    生成认证Token
    :param user_id: int
    :param login_time: int(timestamp)
    :return: string
    """
    try:
        payload = {
            'exp': datetime.datetime.utcnow() + datetime.timedelta(days=0, seconds=10),
            'iat': datetime.datetime.utcnow(),
            'iss': 'ken',
            'data': {
                'id':userid,
                'login_time': logintime
            }
        }
        return jwt.encode(
            payload,
            privatekey,
            algorithm='HS256'
        )
    except Exception  as e:
        return e


def decode_auth_token(auth_token):
    """
    验证Token
    :param auth_token:
    :return: integer|string
    """
    try:
        payload = jwt.decode(auth_token, privatekey, options= {'verify_exp':False})
        if ('data' in payload and 'id' in payload['data']):
            return payload
        else:
            raise jwt.InvalidTokenError

    except jwt.ExpiredSignatureError:
        return "Token过期"
    except jwt.InvalidTokenError:
        return "无效的Token"

def identify(request):
    """
    用户鉴权
    :return: list
    """
    auth_header = request.headers.get('Authorization')
    print(auth_header)
    if (auth_header):
        auth_tokenArr = auth_header.split(" ")
        if (not auth_tokenArr or auth_tokenArr[0]!= 'jwt' or len(auth_tokenArr) != 2 ):
            result = RestEntity(0, 0, "", "请传递正确的验证头信息！")
            return jsonify(result);
            #result = common.falseReturn('','请传递正确的验证头信息')
        else:
            auth_token = auth_tokenArr[1]
            payload = decode_auth_token(auth_token)
            if not isinstance(payload, str):

                #user = User.query.filter_by(user_name='管理员').first()
                #userDao.search(payload['data']['id'])
                #if (user is None):
                #    result = RestEntity(0, 0, "", "找不到该用户信息！")

                    #result = common.falseReturn('', '找不到该用户信息')
                #else:
                result = RestEntity(0, 0, "", "请求成功！")

                    #result = common.trueReturn('', '请求成功')
            else:
                result = RestEntity(0, 0, payload, "")

                #result = common.falseReturn('', payload)
    else:
        result = RestEntity(0, 0, "", "没有提供认证token！")
        print("没有提供认证token！jsonify( result)")
        #result = common.falseReturn('','没有提供认证token')
    return result
